<?php

class UserController extends Zend_Controller_Action
{

  public function init()
  {
    /* Initialize action controller here */
  }

  public function indexAction()
  {
    $viewer = Engine_Api::_()->application()->getViewer();
    if ($viewer) {
      print_die($viewer);
    } else {
      print_die('unlogin');
    }
  }

  public function registrationAction()
  {
    $this->view->form = $form = new Application_Form_Registration();

    if (!$this->getRequest()->isPost() || !$form->isValid($this->getRequest()->getPost()))
      return;

    $user = new Application_Model_User();
    $user->fill($form->getValues());
    $user->password = md5($user->password);
    $user->creation_date = date("Y-m-d H:i:s");
    $user->save();
  }

  public function loginAction()
  {
    $this->view->form = $form = new Application_Form_Auth();
    $user = new Application_Model_User();

    if ($this->getRequest()->isPost()) {
      if ($form->isValid($this->getRequest()->getPost())) {
        if ($user->authorize($form->getValue('email'), $form->getValue('password'))) {
          $user = new Application_Model_User(Zend_Auth::getInstance()->getIdentity()->user_id);
          $user->save();
          $this->_redirect('index/index');
        }
      }
    }
  }

  public function logoutAction()
  {
    Zend_Auth::getInstance()->clearIdentity();
    $this->_redirect('index/index');
  }

  public function uploadPhotoAction()
  {
    $this->view->form = $form = new Application_Form_Upload();

    if ($this->getRequest()->isPost()) {
      if ($form->isValid($this->getRequest()->getPost())) {
        $user = new Application_Model_User(Zend_Auth::getInstance()->getIdentity()->user_id);
        $user->setPhoto($_FILES['image']);
        $user->save();
      }
    }
  }


}

